package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.enums.ResultCodeEnum;
import com.example.entity.Activity;
import com.example.exception.CustomException;
import com.example.mapper.ActivityMapper;
import com.example.service.ActivityService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class ActivityServiceImpl extends ServiceImpl<ActivityMapper, Activity> implements ActivityService {


    @Override
    public void add(Activity activity) {
        Activity item = getBaseMapper().selectOne(buildWrapper(activity));
        if (!Objects.isNull(item)) {
            throw new CustomException(ResultCodeEnum.NAME_EXIST_ERROR);
        }
        getBaseMapper().insert(activity);
    }

    @Override
    public void deleteById(Integer id) {
        getBaseMapper().deleteById(id);
    }

    @Override
    public void deleteBatch(List<Integer> ids) {
        getBaseMapper().deleteBatchIds(ids);
    }

    @Override
    public Activity selectById(Integer id) {
        return getBaseMapper().selectById(id);
    }

    @Override
    public List<Activity> selectAll(Activity activity) {
        return getBaseMapper().selectList(buildWrapper(activity));
    }

    @Override
    public Page<Activity> selectPage(Activity activity, Integer pageNum, Integer pageSize) {
        Page<Activity> page = new Page<>(pageNum, pageSize);
        return getBaseMapper().selectPage(page, buildWrapper(activity));
    }

    /**
     * 热门活动
     */
    @Override
    public List<Activity> selectTop() {
        List<Activity> activityList = this.selectAll(null);
        activityList = activityList.stream().sorted((b1, b2) -> b2.getReadCount().compareTo(b1.getReadCount()))
                .limit(2)
                .collect(Collectors.toList());
        return activityList;
    }

    public LambdaQueryWrapper<Activity> buildWrapper(Activity activity) {
        if (Objects.isNull(activity)) {
            return null;
        }
        LambdaQueryWrapper<Activity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(!Objects.isNull(activity.getName()), Activity::getName, activity.getName());
        return queryWrapper;
    }
}
